/*
XCommander Extension
http://www.xcommander.ch/
*/

function XCommanderXHR() {

}

XCommanderXHR.prototype = {
	_getParams : function(params) {
		var first = true;
		var result = '';
		for(var key in params) {
			if(!first) {
				result += '&';
			}
			result += key + '=' + params[key];
			first = false;
		}
		return result;
	},
	send : function(details, callback) {
		var xhr = new XMLHttpRequest();
		var method = details.method || 'GET';
		var async = details.async || true;
		var params = details.params || null;
		var type = details.type || 'text';
		var url = details.url;
		var username = details.username || '';
		var password = details.password || '';
		if(details.url.indexOf(xcommander.lib.getExtensionScheme()) == 0) {
			url = xcommander.lib.browser.getExtensionUrl(details.url.replace(xcommander.lib.getExtensionScheme(), ''));
		}

		if(params != null) {
			if( typeof details.params == 'object') {
				params = this._getParams(params);
			}
			if(method == 'GET') {
				url = url + '?' + params;
				params = null;
			}
		}

		try {
			xhr.open(method, url, async, username, password);
		} catch(e) {
			callback(getErrorResult());
			return getErrorResult();
		}

		if( typeof xhr.overrideMimeType != 'undefined') {
			if(type == 'json') {
				xhr.overrideMimeType('application/json');
			}
		}

		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4) {
				if( typeof callback == 'function' || ( typeof callback.call != 'undefined' && typeof callback.apply != 'undefined')) {
					callback(getResult(xhr, type));
				}
			}
		};
		if( typeof details.headers == 'object') {
			for(var key in details.headers) {
				xhr.setRequestHeader(key, details.headers[key]);
			}
		}

		try {
			xhr.send(params);
		} catch(e) {
			callback(getErrorResult());
			return getErrorResult();
		}

		return getResult(xhr, type);

		function getResult(xhr, type) {
			var data = {
				response : null,
				status : 0
			};
			if(xhr.readyState >= 2) {
				data.status = xhr.status;
				if(xhr.readyState == 4) {
					if(type == 'xml') {
						data.response = xhr.responseXML;
					} else if(type == 'json') {
						try {
							data.response = JSON.parse(xhr.responseText);
						} catch(e) {
							//ignore
						}
					} else {
						data.response = xhr.responseText;
					}
				}
			}
			return JSON.parse(JSON.stringify(data));
		}

		function getErrorResult() {
			return {
				response : null,
				status : 0
			};
		}

	}
};
